package com.mjh.zhujianju.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.livew.framework.base.model.SysUser;
import com.livew.framework.base.service.SysUserService;
import com.livew.framework.pojo.AjaxResult;
import com.livew.framework.pojo.LoginUserInfo;
import com.livew.framework.utils.XTCurrentUser;
import com.livew.framework.utils.XTStringUtils;
import com.mjh.zhujianju.service.agency.DeptUserService;
import com.mjh.zhujianju.util.ShiroEncryption;
import com.mjh.zhujianju.vo.agency.DeptUserVO;

@Controller
@RequestMapping("")
public class LoginController {

	@Resource
	private SysUserService userService;
	
	@Resource
	private DeptUserService  deptUserService ;

	/***
	 * 登录
	 * @param user
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult login(SysUser user, HttpSession session) {
		if (user == null || XTStringUtils.isEmpty(user.getUsername()) || XTStringUtils.isEmpty(user.getPassword())) {
			return AjaxResult.getResult(Boolean.FALSE, "用户名或密码错误！");
		}
		Subject subject = SecurityUtils.getSubject();
		try {
			// 已登陆则 跳到首页
			if (subject.isAuthenticated()) {
				return AjaxResult.getResult(Boolean.TRUE, "登录成功");
			}
			String password = ShiroEncryption.encrptText(user.getPassword());
			// 身份验证
			subject.login(new UsernamePasswordToken(user.getUsername(), password));
		} catch (AuthenticationException e) {
			// 身份验证失败
			return AjaxResult.getResult(Boolean.FALSE, e.getMessage());
		}
		LoginUserInfo info = XTCurrentUser.getCurrentUser();
		if(info!=null) {
		DeptUserVO dept =	deptUserService.getDeptByUserId(info.getId());
		if(dept!=null) {
			info.setDeptId(dept.getDeptId());
			info.setDeptName(dept.getDeptName());
		}
		}
		return AjaxResult.getResult(Boolean.TRUE, "登录成功");
	}

	/**
	 * 登录页面
	 * @return
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String notLogin() {
		Subject subject = SecurityUtils.getSubject();
		// 已登陆则 跳到首页
		if (subject.isAuthenticated()) {
			return "redirect:/agency/index";
		}
		return "/login";
	}

	@RequestMapping("/logout")
	public String logOut(HttpSession session) {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "login";
	}
	
	
	@RequestMapping("/403")
	public String un403() {
		
		return "403";
	}

	
	
}
